import paramiko


class SSHConnect:
    _transport = None

    def __init__(self, host, port, user, private_key_path):
        self.host = host
        self.port = port
        self.user = user
        self.private_key_path = private_key_path

        self.connect()

    def connect(self):
        try:
            # 创建SSH连接
            self._transport = paramiko.Transport((self.host, self.port))

            # 加载私钥
            mykey = paramiko.RSAKey(filename=self.private_key_path)

            # 连接并进行身份验证
            self._transport.connect(username=self.user, pkey=mykey)

        except Exception as e:
            print("SSH connection failed: " + str(e))

    def exec(self, command):
        ssh = paramiko.SSHClient()

        ssh._transport = self._transport

        stdin, stdout, stderr = ssh.exec_command(command)

        res = stdout.read().decode('utf-8')

        error = stderr.read().decode('utf-8')

        if error.strip():
            return error
        else:
            return res

    # 文件上传
    def sftp_put(self, local_path, remote_path):
        try:
            # 文件上传
            sftp = self._transport.open_sftp_client()
            sftp.put(local_path, remote_path)
            print(
                f"File '{local_path}' uploaded to '{remote_path}' successfully.")
        except Exception as e:
            print(
                f"Failed to upload file '{local_path}' to '{remote_path}': {str(e)}")

    def close(self):
        if self._transport:
            self._transport.close()



def upload_file(ssh_params):
    ssh = SSHConnect(ssh_params["host"], ssh_params["port"], ssh_params["user"], ssh_params["private_key_path"])

    # 使用SSH连接执行cd命令进入目录，然后执行ls命令来列出目录中的文件
    cd_command = f"cd {ssh_params['remote_directory']} && rm -rf * && ls -al"
    result = ssh.exec(cd_command)

    remote_zip_path = f'{ssh_params["remote_directory"]}/{ssh_params["out_dir"]}.zip'
    try:
        ssh.sftp_put(ssh_params['local_zip_path'], remote_zip_path)
        print(f'Successfully uploaded {ssh_params["local_zip_path"]} to {remote_zip_path}')

    # 在服务器上执行解压命令
        unzip_command = f"unzip {remote_zip_path} -d {ssh_params['remote_directory']}"
        unzip_result = ssh.exec(unzip_command)
    except Exception as e:
        print(f'Failed to upload and unzip {ssh_params["local_zip_path"]}: {str(e)}')

    # 关闭SSH连接
    ssh.close()

